//
//  AppDelegate.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 17/4/5.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "AppDelegate.h"
#import "EWLoginViewController.h"
#import <RongIMLib/RongIMLib.h>
#import <RongIMKit/RongIMKit.h>
#import <UMSocialCore/UMSocialCore.h>
#import "EWTabBarController.h"
#import "RCDRCIMDataSource.h"
#import "RCDUtilities.h"
#import "SortForTime.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //初始化融云相关设置
    [self configRongYunSDK];
    //初始化友盟分享相关设置
    [self configUMengSDK];
    //初始化MOB
    [SMSSDK registerApp:@"1cebb519dfb10" withSecret:@"f197e7526366df6298a1e3cda6f77ce0"];
    
    self.window = [[UIWindow alloc] init];
    
    NSString *token = [DEFAULTS objectForKey:@"loginToken"];
    if (token.length != 0) {
        EWTabBarController *baseTabBarController = [[EWTabBarController alloc] init];
        self.window.rootViewController = baseTabBarController;
    }
    else
    {
        EWLoginViewController *loginVC = [[EWLoginViewController alloc] init];
        self.window.rootViewController = loginVC;
    }
    //连接融云服务器
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        NSLog(@"userId=%@",userId);
        //设置当前登录用户信息
        RCUserInfo *user = [[RCDataBaseManager shareInstance] getUserByUserId:userId];
        //设置当前登录用户信息
        [RCIM sharedRCIM].currentUserInfo = user;
        
        [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:userId];
        
    } error:^(RCConnectErrorCode status) {
        
    } tokenIncorrect:^{
        
    }];
    
    [[BQLocationManager sharedManager] startUpdatingLocation];
    
    [self.window makeKeyAndVisible];
    
    if ([application
         respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        //注册推送, 用于iOS8以及iOS8之后的系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    /**
     * 统计推送打开率1
     */
    [[RCIMClient sharedRCIMClient] recordLaunchOptionsEvent:launchOptions];
    /**
     * 获取融云推送服务扩展字段1
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient]
                                     getPushExtraFromLaunchOptions:launchOptions];
    if (pushServiceData) {
        NSLog(@"该启动事件包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"%@", pushServiceData[key]);
        }
    } else {
        NSLog(@"该启动事件不包含来自融云的推送服务");
    }

    
    return YES;
}

- (void)configRongYunSDK
{
    //初始化融云SDK
    [[RCIM sharedRCIM] initWithAppKey:@"c9kqb3rdcvvoj"];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveMessageNotification:)
     name:RCKitDispatchMessageNotification
     object:nil];
    
    //开启用户信息和群组信息的持久化
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
    //设置用户信息源和群组信息源
    [RCIM sharedRCIM].userInfoDataSource = RCDDataSource;
    [RCIM sharedRCIM].groupInfoDataSource = RCDDataSource;
    //设置接收消息代理
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    //开启输入状态监听
    [RCIM sharedRCIM].enableTypingStatus = YES;
    
    //设置头像圆角显示
    [RCIM sharedRCIM].globalMessageAvatarStyle = RC_USER_AVATAR_CYCLE;
    [RCIM sharedRCIM].globalConversationAvatarStyle = RC_USER_AVATAR_CYCLE;
    [RCIM sharedRCIM].portraitImageViewCornerRadius = 20;
    [RCIM sharedRCIM].globalConversationPortraitSize = CGSizeMake(40, 40);
    
    //开启发送已读回执
    [RCIM sharedRCIM].enabledReadReceiptConversationTypeList = @[@(ConversationType_PRIVATE),@(ConversationType_DISCUSSION),@(ConversationType_GROUP)];
    
    //开启多端未读状态同步
    [RCIM sharedRCIM].enableSyncReadStatus = YES;
    
    //设置显示未注册的消息
    //如：新版本增加了某种自定义消息，但是老版本不能识别，开发者可以在旧版本中预先自定义这种未识别的消息的显示
    [RCIM sharedRCIM].showUnkownMessage = YES;
    [RCIM sharedRCIM].showUnkownMessageNotificaiton = YES;
    
    //群成员数据源
    [RCIM sharedRCIM].groupMemberDataSource = RCDDataSource;
    
    //开启消息@功能（只支持群聊和讨论组, App需要实现群成员数据源groupMemberDataSource）
    [RCIM sharedRCIM].enableMessageMentioned = YES;
    
    //开启消息撤回功能
    [RCIM sharedRCIM].enableMessageRecall = YES;
}

- (void)configUMengSDK
{
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:@""];
    
    [self configUSharePlatforms];
    
    [self confitUShareSettings];
}

- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
    
}

- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105821097"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    /* 支付宝的appKey */
    [[UMSocialManager defaultManager] setPlaform: UMSocialPlatformType_AlipaySession appKey:@"2015111700822536" appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

//注册用户通知设置
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    // register to receive notifications
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if TARGET_IPHONE_SIMULATOR
    // 模拟器不能使用远程推送
#else
    // 请检查App的APNs的权限设置，更多内容可以参考文档
    // http://www.rongcloud.cn/docs/ios_push.html。
    NSLog(@"获取DeviceToken失败！！！");
    NSLog(@"ERROR：%@", error);
#endif
}

/**
 * 推送处理4
 * userInfo内容请参考官网文档
 */
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    /**
     * 统计推送打开率2
     */
    [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
    /**
     * 获取融云推送服务扩展字段2
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient]
                                     getPushExtraFromRemoteNotification:userInfo];
    if (pushServiceData) {
        NSLog(@"该远程推送包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"key = %@, value = %@", key, pushServiceData[key]);
        }
    } else {
        NSLog(@"该远程推送不包含来自融云的推送服务");
    }
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    /**
     * 统计推送打开率3
     */
    [[RCIMClient sharedRCIMClient] recordLocalNotificationEvent:notification];
    
    //  //震动
    //  AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //  AudioServicesPlaySystemSound(1007);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state.
    // This can occur for certain types of temporary interruptions (such as an
    // incoming phone call or SMS message) or when the user quits the application
    // and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down
    // OpenGL ES frame rates. Games should use this method to pause the game.
    RCConnectionStatus status = [[RCIMClient sharedRCIMClient] getConnectionStatus];
    if (status != ConnectionStatus_SignUp) {
        int unreadMsgCount = [[RCIMClient sharedRCIMClient]
                              getUnreadCount:@[
                                               @(ConversationType_PRIVATE),
                                               @(ConversationType_DISCUSSION),
                                               @(ConversationType_APPSERVICE),
                                               @(ConversationType_PUBLICSERVICE),
                                               @(ConversationType_GROUP)
                                               ]];
        application.applicationIconBadgeNumber = unreadMsgCount;
    }
}

- (void)didReceiveMessageNotification:(NSNotification *)notification {
    NSNumber *left = [notification.userInfo objectForKey:@"left"];
    if ([RCIMClient sharedRCIMClient].sdkRunningMode ==
        RCSDKRunningMode_Background &&
        0 == left.integerValue) {
        int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                             @(ConversationType_PRIVATE),
                                                                             @(ConversationType_DISCUSSION),
                                                                             @(ConversationType_APPSERVICE),
                                                                             @(ConversationType_PUBLICSERVICE),
                                                                             @(ConversationType_GROUP)
                                                                             ]];
        [UIApplication sharedApplication].applicationIconBadgeNumber =
        unreadMsgCount;
    }
}

/**
 *  网络状态变化。
 *
 *  @param status 网络状态。
 */
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"提示"
                              message:
                              @"您的帐号在别的设备上登录，"
                              @"您被迫下线！"
                              delegate:nil
                              cancelButtonTitle:@"知道了"
                              otherButtonTitles:nil, nil];
        [alert show];
        EWLoginViewController *loginVC = [[EWLoginViewController alloc] init];
        self.window.rootViewController = loginVC;
    } else if (status == ConnectionStatus_TOKEN_INCORRECT) {
        
    }
}

- (BOOL)onRCIMCustomLocalNotification:(RCMessage*)message
withSenderName:(NSString *)senderName{
    //群组通知不弹本地通知
    if ([message.content isKindOfClass:[RCGroupNotificationMessage class]]) {
        return YES;
    }
    return NO;
}

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    if ([message.content
         isMemberOfClass:[RCInformationNotificationMessage class]]) {
        RCInformationNotificationMessage *msg =
        (RCInformationNotificationMessage *)message.content;
        // NSString *str = [NSString stringWithFormat:@"%@",msg.message];
        if ([msg.message rangeOfString:@"你已添加了"].location != NSNotFound) {
            [[RCDRCIMDataSource shareInstance] syncFriendList:[RCIM sharedRCIM].currentUserInfo.userId complete:^(NSMutableArray *friends){
                
            }];
        }
    } else if ([message.content
                isMemberOfClass:[RCContactNotificationMessage class]]) {
        RCContactNotificationMessage *msg = (RCContactNotificationMessage *)message.content;
        if ([msg.operation isEqualToString:@"Request"]) {
            [[RCDRCIMDataSource shareInstance] syncFriendList:[RCIM sharedRCIM].currentUserInfo.userId complete:^(NSMutableArray *friends){
                
            }];
        }
        if ([msg.operation isEqualToString:@"AcceptResponse"]) {
            [[RCDRCIMDataSource shareInstance] syncFriendList:[RCIM sharedRCIM].currentUserInfo.userId complete:^(NSMutableArray *friends){
                
            }];
        }
    } else if ([message.content
                isMemberOfClass:[RCGroupNotificationMessage class]]) {
        RCGroupNotificationMessage *msg =
        (RCGroupNotificationMessage *)message.content;
        if ([msg.operation isEqualToString:@"Dismiss"]) {
            //清除群组图片的缓存
            RCDGroupInfo *groupInfo = [[RCDataBaseManager shareInstance] getGroupByGroupId:message.targetId];
            [[SDImageCache sharedImageCache] removeImageForKey:groupInfo.portraitUri withCompletion:^{
                
            }];
            
            [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_GROUP
                                                targetId:message.targetId];
            [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_GROUP
                                                     targetId:message.targetId];
            [[RCDataBaseManager shareInstance] deleteGroupToDB:message.targetId];
        }
        else if ([msg.operation isEqualToString:@"Add"])
        {
            [RCDDataSource syncGroupMembersWithGroupId:message.targetId complete:^(BOOL result) {
                
            }];
            
        }
        else if ([msg.operation isEqualToString:@"Kicked"])
        {
            if ([msg.extra isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_GROUP
                                                    targetId:message.targetId];
                [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_GROUP
                                                         targetId:message.targetId];
                [[RCDataBaseManager shareInstance] deleteGroupToDB:message.targetId];
                
            }
            else
            {
                [RCDDataSource syncGroupMembersWithGroupId:message.targetId complete:^(BOOL result) {
                    
                }];
            }
            
        }
        else if ([msg.operation isEqualToString:@"Quit"])
        {
            //清除群组图片的缓存
            RCDGroupInfo *groupInfo = [[RCDataBaseManager shareInstance] getGroupByGroupId:message.targetId];
            [[SDImageCache sharedImageCache] removeImageForKey:groupInfo.portraitUri withCompletion:^{
                
            }];
            
            [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_GROUP
                                                targetId:message.targetId];
            [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_GROUP
                                                     targetId:message.targetId];
            [[RCDataBaseManager shareInstance] deleteGroupToDB:message.targetId];
        }
    }
    else if ([message.content isMemberOfClass:[RCCommandMessage class]])
    {
        RCCommandMessage *msg = (RCCommandMessage *)message.content;
        if ([msg.name isEqualToString:@"UpdateUserInfo"]) {
            [RCDDataSource syncUserInfoWithUserId:msg.data complete:^(BOOL result) {
                
                RCUserInfo *userInfo = [[RCDataBaseManager shareInstance] getUserByUserId:msg.data];
                //清除SDWebImage缓存
                [[SDImageCache sharedImageCache] removeImageForKey:userInfo.portraitUri withCompletion:^{
                }];
                
                
            }];
        }
        else if ([msg.name isEqualToString:@"UpdateGroupMemberInfo"])
        {
            NSArray *idList = [msg.data componentsSeparatedByString:@","];
            RCUserInfo *friendOldInfo = [[RCDataBaseManager shareInstance] getUserByUserId:[idList lastObject]];
            
            [[SDImageCache sharedImageCache] removeImageForKey:friendOldInfo.portraitUri withCompletion:^{
                
            }];
            
            [RCDDataSource syncUserInfoWithUserId:[idList lastObject] complete:^(BOOL result) {
                RCUserInfo *friendInfo = [[RCDataBaseManager shareInstance] getUserByUserId:[idList lastObject]];
                RCDUserInfo *userInfo = [[RCDataBaseManager shareInstance] getFriendInfo:[idList lastObject]];
                if (userInfo.userId.length > 0 && userInfo.name.length > 0) {
                    friendInfo.userId = userInfo.userId;
                    friendInfo.name = userInfo.name;
                    friendInfo.portraitUri = userInfo.portraitUri;
                }
                for (int i = 0; i < idList.count - 1; i++) {
                    NSString *groupId = idList[i];
                    [[RCDataBaseManager shareInstance] insertGroupMemberToDB:friendInfo groupId:groupId complete:^(BOOL result) {
                        if (result) {
                            [[RCIM sharedRCIM] refreshGroupUserInfoCache:friendInfo withUserId:friendInfo.userId withGroupId:groupId];
                        }
                    }];
                }
            }];
            
        }
        else if ([msg.name isEqualToString:@"UpdateGroupInfo"])
        {
            RCDGroupInfo *groupInfo = [[RCDataBaseManager shareInstance] getGroupByGroupId:msg.data];
            //删除旧的群图片缓存
            [[SDImageCache sharedImageCache] removeImageForKey:groupInfo.portraitUri withCompletion:^{
                //更新群组信息
                [RCDDataSource syncGroupInfoWithGroupId:msg.data complete:^(BOOL result) {
                    
                }];
            }];
        }
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:RCKitDispatchMessageNotification
     object:nil];
}


@end
